<script setup>
import { ref, watch, nextTick, onMounted } from "vue"
import { MdPreview } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { useUserStore } from '@/stores/user'

import { fetchEventSource } from '@microsoft/fetch-event-source';
import ChatDialogList from './chat/ChatDialogList.vue'


const textarea = ref("")
const user_input = ref('')
var controller = null

const dialog_uid = ref(null)
const chatContainer = ref(null)

const thinking = ref(false)
const thinkingMsg = ref('思考中...')
const drawer = ref(false)


const start_sse = () =>{

    const userStore = useUserStore();

    thinking.value = true
  controller = new AbortController();
  try{
    fetchEventSource('/api/v1/chat', {

      method: 'POST',
      headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer '+ userStore.access_token
      },
      openWhenHidden: true,
      body: JSON.stringify({
        user_input: user_input.value,
        dialog_uid: dialog_uid.value
      }),
      signal: controller.signal,

      async onopen(response) {
        console.log('连接已建立', response);
        
        if (response.ok && response.headers.get('content-type') === 'text/event-stream; charset=utf-8') {
          return; // 连接成功
        } else {
          const errorData = await response.json();
          console.log(errorData.message)
          thinking.value = false
          // throw new Error('连接失败---');
          return 
        }
      },
      onmessage(msg) {
          // if the server emits an error message, throw an exception
          // so it gets handled by the onerror callback below:
        //   console.log(msg.data)
        //   sse_comtent.value = msg
        try{
            var msg_data = JSON.parse(msg.data)
            dialog_uid.value = msg_data.dialog_uid
            if (msg_data.event=='start'){
                thinkingMsg.value = '思考中...'
                cahtHistory.value.push({'role': 'assistant', 'content': ''})
            }else if (msg_data.event=='continue'){
                thinkingMsg.value = '思考中...'
                // console.log(cahtHistory.value)
                cahtHistory.value[cahtHistory.value.length - 1].content += msg_data.data
            }else if (msg_data.event=='tools'){
                thinkingMsg.value = '调用工具...'
            }else if (msg_data.event=='end'){
                thinkingMsg.value = '思考中...'
            }

        }catch{
            
        }
        


      },
      onclose() {
          // if the server closes the connection unexpectedly, retry:
          console.log('连接已关闭');
          thinking.value = false
          return true
      },
      onerror(err) {
        // console.error('发生错误:', err);
        thinking.value = false
        throw err
        
      },
      
      })

  } catch (err) {
    console.log(err)
  }

}

const cahtHistory = ref([])


const submit_input = ()=>{

    cahtHistory.value.push({'role': 'user', 'content': textarea.value})
    user_input.value = textarea.value
    textarea.value = ''
    start_sse()

}

const open_new_dialog = ()=>{
    cahtHistory.value = []
    thinking.value = false
    controller = null
    dialog_uid.value = null
}

const open_drawer = ()=>{
    
    drawer.value = true
}

const scrollToBottom = () => {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

const handleDoubleClick = (dialog_item)=>{
    cahtHistory.value = []
    dialog_uid.value = dialog_item.dialog_uid
    cahtHistory.value = dialog_item.history_list
    drawer.value = false
}
 
// 监听对话历史变化，自动滚动到底部
watch(cahtHistory, () => {
  nextTick(scrollToBottom) // 关键：等待DOM更新后再滚动
}, { deep: true })


onMounted(()=>{
        
    })

</script>

<template>
    <div  ref="chatContainer" class="body_content_chat">
        
        <div class="chat__container">
            <div class="ai__chat">
                <div v-for="item, index in cahtHistory" :key="index" class="message__container">
                    
                    <!-- 用户消息 -->
                    <div v-if="item.role=='user'" class="user__message">
                        <div class="message__bubble">
                            <div class="message__content">
                                <p>{{ item.content }}</p>
                            </div>
                        </div>
                    </div>

                    <!-- AI消息 -->
                    <div v-else  class="ai__message">
                        <div class="message__bubble__container">
                            <div class="message__title"><span>AI助手</span><div  v-if="index==cahtHistory.length-1 && thinking" class="message_tips"><div class="spinner"></div><div>{{ thinkingMsg }}</div></div></div>
                            <div class="message__bubble">
                                <div class="message__content">
                                    <MdPreview
                                    :id="`mars-output-${index}`" :modelValue="item.content" :showCodeRowNumber="true"
                                    />
                                </div>
                            </div>
                        </div>
                        
                    </div>

                </div>

            </div>


        </div>
        
        <div class="chat__input">

        <div class="chat__input_cantainer">

            <div class="user__input">
                
                <el-input
                    type="textarea"
                    :rows="3"

                    placeholder="和我聊聊天吧"
                    resize="none"
                    v-model="textarea">
                    </el-input>
            </div>
            <div class="user__tools">
                <div class="btn new__dialog" @click="open_new_dialog" >
                    开启新的对话
                </div>
                <div class="btn dialog__record" @click="open_drawer">
                    聊天记录
                </div>
                <div class="submit__btn" @click="submit_input">
                    发送
                </div>
                
            </div>
            
        </div>

        </div>
        
    
    </div>

    <el-drawer
        title="我是标题"
        v-model="drawer"
        :with-header="false">
        <ChatDialogList
        message_type="Agent"
        @handleDoubleClick="handleDoubleClick"
        ></ChatDialogList>
        </el-drawer>

</template>

<style scoped lang="scss">

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.spinner {
    border: 2px solid rgba(0, 0, 0, 0.1);
  width: 15px;
  height: 15px;
  border-radius: 50%;
  border-left-color: #09f;
  animation: spin 1s infinite linear; 
  margin-right: 4px;

}


:deep(.el-textarea__inner){
    box-shadow: none;
    
}
.body_content_chat{
    width: 100%;
    height: 100%;
    text-align: left;
    
    // position: relative;
    overflow-y: auto;
}
.chat__container{
    padding: 20PX;
    // height: calc(100% - 200px);
    padding-bottom: 220px;
    .ai__chat{
        display: flex;
        flex-direction: column;
        gap: 20px;
    }
}

.message__container{
    
    .user__message{
        display: flex;
        justify-content: flex-end;
        
        .message__bubble{
            border: 1px solid rgb(184, 184, 184);
            padding: 5PX 10px;
            border-radius: 10PX;
            max-width: 80%;
            
        }
        
    }
    .ai__message{
        display: flex;
        justify-content: flex-start;
        
        .message__bubble__container{
            border: 1px solid rgb(184, 184, 184);
            border-radius: 10PX;
            .message__title{
                display: flex;
                align-content: center;
                border-bottom: 1px solid rgb(184, 184, 184);
                height: 30px;
                padding: 0 8px;
                align-content: center;
                font-weight: 600;
                span{
                    align-content: center;
                }
                .message_tips{
                    display: flex;
                    margin-left: 10px;
                    font-size: 10px;
                    color: rgb(184, 184, 184);
                    align-items: center;
                    div{
                        align-content: center;
                    }
                }
            }
            
            .message__bubble{
                padding: 8px;
                
            }
        }
        
        
        
    }


}

.chat__input{
    position: absolute;
    bottom: 0;
    
    width: calc(100% - 200px);
    height: 200px;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    padding-bottom: 30px;
    background-color: transparent;
    

    .chat__input_cantainer{
        border: 1px solid rgb(184, 184, 184);
        height: 100%;
        width: 70%;
        border-radius: 20px;
        background-color: white;
        display: flex;
        flex-direction: column;

        .user__input{
            width: 100%;
            height: calc(100% - 50px);
            padding: 10px;
        }

        .user__tools{
            position: relative;
            width: 100%;
            height: 50px;
            display: flex;
            // justify-content: flex-end;
            align-items: center;
            // padding-right: 15px;
            // gap: 10px;
            .btn{
                cursor: pointer;
                margin-left: 15px;
                height: 40px;
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: #09f;
                border-radius: 15px;
                padding: 0 10px;
                color: #fff;
            }
            .new__dialog{
                background-color: rgb(216, 119, 22);
            }
            .dialog__record{
                background-color: rgb(202, 199, 196)
            }

            .submit__btn{
                position: absolute;
                right: 15px;
                color: #fff;
                cursor: pointer;
                width: 60px;
                height: 40px;
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: #09f;
                border-radius: 20px;
            }
        }
        
    }
    
}
</style>

<style>
.md-editor-preview {
    font-size: 12px;
    word-break: break-all;
    display: flow-root;
    padding: 5px 10px;
}

</style>